#include <stdio.h>
#include "i2c.h"
#include "tw9900.h"

#define I2C_ADDR 	0x45

static int i2c_read_byte(uint8_t reg, uint8_t *data)
{
    i2c_t *i2c;

    i2c = i2c_new();

    /* Open the i2c-1 bus */
    if (i2c_open(i2c, "/dev/i2c-1") < 0) {
        fprintf(stderr, "i2c_open(): %s\n", i2c_errmsg(i2c));
        i2c_free(i2c);
        return -1;
    }

    uint8_t msg_addr[1] = { reg };
    struct i2c_msg msgs[2] =
        {
			/* Write 8-bit address */
            { .addr = I2C_ADDR, .flags = 0, .len = 1, .buf = msg_addr },
			/* Read 8-bit data */
			{ .addr = I2C_ADDR, .flags = I2C_M_RD, .len = 1, .buf = data },
        };

    /* Transfer a transaction with two I2C messages */
    if (i2c_transfer(i2c, msgs, 2) < 0) {
        fprintf(stderr, "i2c_transfer(): %s\n", i2c_errmsg(i2c));
        i2c_close(i2c);
        i2c_free(i2c);
        return -1;
    }

    i2c_close(i2c);
    i2c_free(i2c);

    return 0;
}

int tw9900_detect_video_input(void)
{
    uint8_t reg_val = 0;
    i2c_read_byte(0x01, &reg_val);
    /*  bit7 为0，  bit3 为1 . 判断为有视频接入了。 */
    if (0 == ((reg_val >> 7) & 0x01) && 1 == ((reg_val >> 3) & 0x01)) {
        return 1;
    }

    return 0;
}